//
//  CalendarViewController.m
//  FootPrint
//
//  Created by alex tao on 2/25/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "CalendarViewController.h"
#import "ITTBaseDataSourceImp.h"
#import "ITTBaseCalendarViewHeaderView.h"
#import "ITTBaseCalendarGridView.h"
#import "ITTBaseCalendarDisableGridView.h"
#import "EventGridCell.h"
#import "EventDetailViewController.h"
//#import "ITTBaseCalendarViewFooterView.h"

@interface CalendarViewController ()

@end

@implementation CalendarViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _calType = eCalendarView;
        
        _formatter = [[NSDateFormatter alloc] init];
        [_formatter setDateFormat:@"HH 点 mm 分"];
        
        _parser = [[EventListParser alloc] init];
        _parser.delegate = self;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    if (eCalendarView == _calType) {
        _backBtn.hidden = YES;
        _okBtn.hidden = YES;
    } else {
        _backBtn.hidden = NO;
        _okBtn.hidden = NO;
    }
    
    _gridScroll.gridDelegate = self;
    
    _calendarView = [ITTCalendarView viewFromNib];
    _calendarView.minimumDate = nil;
    _calendarView.date = _selDate ? _selDate : [NSDate date];
    _calendarView.dataSource = self;
    _calendarView.delegate = self;
    _calendarView.frame = _calendarContainer.bounds;
    [_calendarView showInView:_calendarContainer];
    
    UITapGestureRecognizer * tapGesture = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnFooter)] autorelease];
    [self.footerView addGestureRecognizer:tapGesture];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_parser dealloc];
    [_timePicker release];
    [_dateComponent release];
    [_formatter release];
    [_selDate release];
    [_calendarContainer release];
    [_gridScroll release];
    [_footerView release];
    [_timeLabel release];
    [_backBtn release];
    [_okBtn release];
    [super dealloc];
}

- (void)viewDidUnload {
    [self setCalendarContainer:nil];
    [self setGridScroll:nil];
    [self setFooterView:nil];
    [self setTimeLabel:nil];
    [self setBackBtn:nil];
    [self setOkBtn:nil];
    [super viewDidUnload];
}

- (void)updateTimeLabel:(NSDate*)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
    NSDateComponents * timeComp = [calendar components:unitFlags fromDate:date];
    
    [_dateComponent setHour:timeComp.hour];
    [_dateComponent setMinute:timeComp.minute];
    [_dateComponent setSecond:timeComp.second];
    
    _timeLabel.text = [_formatter stringFromDate:date];
}

- (void)tapOnFooter
{
    if (nil == _timePicker) {
        _timePicker = [[TimePicker alloc] initWithFrame:self.view.bounds];
        __block CalendarViewController * nonRetailSelf = self;
        [_timePicker setPickBlock:^(NSDate* date) {
            [nonRetailSelf updateTimeLabel:date];
        }];
    }
    _timePicker.picker.date = _selDate;
    [self.view addSubview:_timePicker];
}

- (IBAction)goBack:(id)sender {
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
}

- (IBAction)okSelect:(id)sender
{
    NSDate * pickDate = [[NSCalendar currentCalendar] dateFromComponents:_dateComponent];
    if (NSOrderedAscending == [pickDate compare:[NSDate date]]) {
        [[iToast makeText:@"不能选择过去的时间"] show];
        return;
    }
    
    if ([_pickDelegate respondsToSelector:@selector(calendarDidPickDate:)]) {
        [_pickDelegate calendarDidPickDate:pickDate];
    }
    [self goBack:nil];
}

- (void) calPickModeWithDate:(NSDate*)date update:(BOOL)ifUpdate
{
    if (nil == date) {
        date = [NSDate date];
    }
    _calType = eCalendarSelect;
    
    [_selDate release];
    _selDate = [date retain];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
    [_dateComponent release];
    _dateComponent = [[calendar components:unitFlags fromDate:date] retain];
    
    if (ifUpdate) {
        _backBtn.hidden = NO;
        _okBtn.hidden = NO;
        _calendarView.date = _selDate;
        [_calendarView refresh];
    }
}

- (void) viewMode:(BOOL)ifUpdate
{
    _calType = eCalendarView;
    if (ifUpdate) {
        _backBtn.hidden = YES;
        _okBtn.hidden = YES;
        [_calendarView refresh];
    }
}

- (void) updateCalendarData
{
    [_parser quaryEventByUser:[GConfig getUserId] beginDate:0 endDate:99999999999999 andFilter:@"0000"];
}

- (NSString*) stringFromFomate:(NSDate*) date formate:(NSString*)formate
{
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:formate];
	NSString *str = [formatter stringFromDate:date];
	[formatter release];
	return str;
}


#pragma mark - GridScrollDelegate

- (void) didSelect:(GridScrollView *)gridScroll atTotalIndex :(NSInteger)idx
{
    EventGridCell * cell = [_gridScroll.cells objectAtIndex:idx];
    EventQueryResponseMessage_Summary * eventMsg = cell.eventSummary;
    
    EventDetailViewController * detail = [[[EventDetailViewController alloc] initWithNibName:@"EventDetailViewController" bundle:nil] autorelease];
    
    UINavigationController * navVc = self.navigationController;
    if (nil == navVc) {
        navVc = [[[UINavigationController alloc] initWithRootViewController:detail] autorelease];
        navVc.navigationBarHidden = YES;
        [ROOT_VC presentModalViewController:navVc animated:YES];
    } else {
        [navVc pushViewController:detail animated:YES];
    }
    
    [detail requestById:eventMsg.eventId];
}


#pragma mark - ITTCalendarViewDelegate

- (void)calendarViewDidClickDay:(ITTCalendarView*)calendarView calDay:(ITTCalDay*)calDay
{
    NSLog(@"selected date %@", [self stringFromFomate:calDay.date formate:@"yyyy-MM-dd"]);
    
    _dateComponent.year = [calDay getYear];
    _dateComponent.month = [calDay getMonth];
    _dateComponent.day = [calDay getDay];
    
    long long beginTime = ((long long)[calDay getYear]*10000 + (long long)[calDay getMonth]*100 + (long long)[calDay getDay]) * 1000000;
    long long endTime = beginTime + 235959;
    
    NSMutableArray * eventViews = [[[NSMutableArray alloc] initWithCapacity:2] autorelease];
    for (EventQueryResponseMessage_Summary * msg in self.allEventList) {
        if (msg.time >= beginTime && msg.time <= endTime) {
            EventGridCell * cell = [[[EventGridCell alloc] initWithFrame:CGRectMake(0, 0, 80, 80)] autorelease];
            cell.eventSummary = msg;
            [eventViews addObject:cell];
        }
    }
    
    _gridScroll.cells = eventViews;
}

- (void)calendarViewDidUpdateFrame:(ITTCalendarView*)calendarView
{
    CGRect containerFrame = _calendarContainer.frame;
    containerFrame.size.height = calendarView.frame.size.height;
    _calendarContainer.frame = containerFrame;
    
    CGRect gridRc = _gridScroll.frame;
    gridRc.origin.y = CGRectGetMaxY(_calendarContainer.frame);
    gridRc.size.height = self.view.bounds.size.height - gridRc.origin.y;
    _gridScroll.frame = gridRc;
}


#pragma mark - EventListDelegate

- (void) didRecieveEventList:(EventQueryResponseMessage*)event beginDate:(long long)bgDate endDate:(long long)edDate withFilter:(NSString*)filter
{
    if (event && event.resultCode == 0) {
        self.allEventList = [GToolUtil PBArr2NSArr:event.eventSumList];
        [_calendarView refresh];
    }
}


#pragma mark - ITTCalendarViewDataSource

- (ITTCalendarGridView*)calendarView:(ITTCalendarView*)calendarView calendarGridViewForRow:(NSInteger)row column:(NSInteger)column calDay:(ITTCalDay*)calDay
{
    static NSString *identifier = @"BaseCalendarGridView";
    ITTBaseCalendarGridView *gridView = (ITTBaseCalendarGridView*)[calendarView dequeueCalendarGridViewWithIdentifier:identifier];
    if (!gridView) {
        gridView = (ITTBaseCalendarGridView*)[ITTBaseCalendarGridView viewFromNibWithIdentifier:identifier];
    }

    long long beginTime = ((long long)[calDay getYear]*10000 + (long long)[calDay getMonth]*100 + (long long)[calDay getDay]) * 1000000;
    long long endTime = beginTime + 235959;
    
    gridView.idImageView.hidden = YES;
    for (EventMessage * msg in self.allEventList) {
        if (msg.time >= beginTime && msg.time <= endTime) {
            gridView.idImageView.hidden = NO;
            break;
        }
    }
    
    return gridView;
}

- (ITTCalendarGridView*)calendarView:(ITTCalendarView*)calendarView calendarDisableGridViewForRow:(NSInteger)row column:(NSInteger)column calDay:(ITTCalDay*)calDay
{
    static NSString *identifier = @"ITTBaseCalendarDisableGridView";
    ITTCalendarGridView *gridView = [calendarView dequeueCalendarGridViewWithIdentifier:identifier];
    if (!gridView) {
        gridView = [ITTBaseCalendarDisableGridView viewFromNibWithIdentifier:identifier];
    }
    return gridView;
}

- (ITTCalendarViewHeaderView*)headerViewForCalendarView:(ITTCalendarView*)calendarView
{
    return [ITTBaseCalendarViewHeaderView viewFromNib];
}

- (ITTCalendarViewFooterView*)footerViewForCalendarView:(ITTCalendarView*)calendarView
{
    if (eCalendarSelect == _calType && _selDate) {
        _timeLabel.text = [_formatter stringFromDate:_selDate];
        return _footerView;//[ITTBaseCalendarViewFooterView viewFromNib];
    }
    return nil;
}

//- (NSArray*)weekTitlesForCalendarView:(ITTCalendarView*)calendarView
//{
//    return [NSArray arrayWithObjects:@"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
//}
//
//- (NSString*)calendarView:(ITTCalendarView*)calendarView titleForMonth:(ITTCalMonth*)calMonth
//{
//    NSString *title = [NSString stringWithFormat:@"%d年-%d月", [calMonth getYear], [calMonth getMonth]];
//    return title;
//}


@end
